package cn.zhaozhiqi.consumer;

import cn.zhaozhiqi.constants.Constants;
import cn.zhaozhiqi.pojo.domain.PayOrder;
import cn.zhaozhiqi.pojo.order.dto.PayOrderDto;
import cn.zhaozhiqi.service.IPayOrderService;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@RocketMQMessageListener(
        //消费者的名字
        consumerGroup = "consumer-group-pay",
        //主题
        topic = Constants.Mq.CREATE_PAY_TOPIC,
        //tags
        selectorExpression = Constants.Mq.CREATE_PAY_LAG,
        //消息消费模式：默认是CLUSTERING集群，还支持BROADCASTING广播
        messageModel = MessageModel.CLUSTERING
)
//MessageExt:Message对象的子类
public class OrderPayListener implements RocketMQListener<MessageExt> {

    @Autowired
    private IPayOrderService payOrderService;

    @Override
    public void onMessage(MessageExt messageExt) {
        String jsonStr = new String(messageExt.getBody(), StandardCharsets.UTF_8);
        PayOrderDto dto = JSON.parseObject(jsonStr, PayOrderDto.class);
        //需要保证消费消息的幂等性，即首先查一下数据库中是否有这个统一支付单
        PayOrder payOrder = payOrderService.getByOrderNo(dto.getOrderNo());
        //如果存在，那就说明已经存在，直接接收MQ消息
        if (payOrder != null){
            return;
        }
        payOrderService.createPayOrder(dto);
    }
}
